home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12710 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  85 lines

  1. Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
  2. From: gzhjis@ubszh.net.ch (Ian Johnston (by ubsswop))
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Advanced C++ question...
  5. Date: 21 Mar 1996 09:17:26 GMT
  6. Organization: UBS
  7. Distribution: world
  8. Message-ID: <4ir6r6$qoa@ubszh.fh.zh.ubs.com>
  9. References: <4iprfg$1ui@aadt>
  10. NNTP-Posting-Host: nol2179.fh.zh.ubs.com
  11.  
  12. In article <4iprfg$1ui@aadt>, david_hooker@sdt.com writes:
  13. |> Hi all...
  14. |> 
  15. |> I want to write an operator* for a class, but I want to do
  16. |> one of 2 things:
  17. |>    1. Call one of two different operator*'s depending on whether
  18. |>       it is an lvalue or rvalue
  19. |>    OR
  20. |>    2. Somehow determine in the function if it is being used as an
  21. |>       lvalue or an rvalue.
  22. |> 
  23. |> For instance, I want to know, in the operator*, from which case I'm
  24. |> being called:
  25. |> 
  26. |>   *Object = SomeValue;     // used as an lvalue
  27. |> 
  28. |>    SomeValue = *Object;    // used as an rvalue
  29.  
  30. Instead of your operator * returning a reference to the object, have it
  31. return an instance of a helper class. This helper class has operator =
  32. and operator T. For example:
  33.  
  34.  
  35. class ThingRef;
  36.  
  37. class Thing
  38. {
  39.   public:
  40.     // Usual members...
  41.     ThingRef operator *();
  42. };
  43.  
  44.  
  45. class ThingRef
  46. {
  47.   public:
  48.     ThingRef(Thing &t);
  49.     void operator = (Thing const &value);
  50.     operator Thing &();
  51.  
  52.   private:
  53.     Thing &ref;
  54. };
  55.  
  56.  
  57. ThingRef Thing::operator *()
  58. {
  59.     return ThingRef(*this);
  60. }
  61.  
  62.  
  63. ThingRef::ThingRef(Thing &t)
  64.     : ref(t)
  65. {
  66. }
  67.  
  68. void ThingRef::operator = (Thing const &value)
  69. {
  70.     // Use as an lvalue.
  71.     ref = value;
  72. }
  73.  
  74. ThingRef::operator Thing &()
  75. {
  76.    // Use as an rvalue.
  77.     return ref;
  78. }
  79.  
  80.  
  81. Inlining the ThingRef class may help if you find there is a performance
  82. hit here.
  83.  
  84. Ian
  85.